package com.huang.security.extension.mobile;

import cn.hutool.core.util.StrUtil;
import com.huang.constant.Common;
import com.huang.security.service.CustomUserDetailsService;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 短信验证码认证授权提供者
 *
 * @author han
 * @since  2021/9/25
 */
@Component
public class SmsCodeAuthenticationProvider implements AuthenticationProvider {

    @Resource
    private CustomUserDetailsService customUserDetailsService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        SmsCodeAuthenticationToken authenticationToken = (SmsCodeAuthenticationToken) authentication;
        String mobile = (String) authenticationToken.getPrincipal();
        String code = (String) authenticationToken.getCredentials();

        // 666666 是后门，因为短信收费，正式环境删除这个if分支
        if (!code.equals("666666")) {
            String codeKey = Common.Login.SMS_CODE_PREFIX + mobile;
            String correctCode = stringRedisTemplate.opsForValue().get(codeKey);
            // 验证码比对
            if (StrUtil.isBlank(correctCode) || !code.equals(correctCode)) {
                throw new BadCredentialsException("验证码不正确");
            }
            // 比对成功删除缓存的验证码
            stringRedisTemplate.delete(codeKey);
        }
        UserDetails userDetails = customUserDetailsService.loadUserByMobile(mobile);
        SmsCodeAuthenticationToken result = new SmsCodeAuthenticationToken(userDetails, authentication.getCredentials(), userDetails.getAuthorities());
        result.setDetails(authentication.getDetails());
        return result;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return SmsCodeAuthenticationToken.class.isAssignableFrom(authentication);
    }
}
